var map;
var infoWindow;
var myMarker;
var markersArray = [];
var pointsMarcadores= [];
var myLatLng;

var puntosEntreOrigenDestino_aleatorio=[];
var puntosEntreOrigenDestino_rango_superior = 20;
var puntosEntreOrigenDestino_rango_inferior = 10;
var minimoEntreOrigenDestino;
var llegadaDelPrimerToro=0;
 //animate
 var step = 5; // metres default 5
 var tick = 1000; // milliseconds
 var stepnum=0;
 var timer;//timeout animate
 //var timerGeoLocation;//timeout geolocation
 //var puntosEntreOrigenDestino=30;
 //var puntosEntreOrigenDestino=[];


function initialize() {

 if (navigator.geolocation) {
  /*var myOptions = {
      zoom: 17,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    if(typeof(map)=== "undefined") {
      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }else{
      map.setOptions(myOptions);  
    }*/

  navigator.geolocation.getCurrentPosition(success, error);
   // timeout at 60000 milliseconds (60 seconds)
   /*var timeoutVal = 10 * 1000 * 1000;
      var options = {enableHighAccuracy:false, maximumAge:5000,timeout:timeoutVal};
      
      geoLoc = navigator.geolocation;
      watchID = geoLoc.watchPosition(success, 
                                     error,
                                     options);*/
  
      

} else {
  
  alert('not supported');
}

function error(msg) {
 alert(msg);
}

function success(position) {
  longi=position.coords.longitude;
  latitud=position.coords.latitude;
  
  moverme(latitud,longi );
  
  //timerGeoLocation=setInterval("initialize()",3000);
}

}


function moverme(latitud, longi){
  //document.title=position.coords.speed;
  myLatLng = new google.maps.LatLng(latitud, longi);
  var myOptions = {
      zoom: 17,
      center: myLatLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    if(typeof(map)=== "undefined") {
      map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }else{
      map.setOptions(myOptions);  
    }
    //map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    


    

    if(typeof(myMarker) === "undefined"){
      
      var image = 'img/redbull/personaje.png';
      myMarker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image
    });    
      
      
    }/*else{
      clearInterval(timer);
      myMarker.setPosition(myLatLng);
      refreshRutaAToros();
      //timer =setTimeout("animateMarkers()",tick);  // Allow time for the initial map display
      timer=setInterval("animateMarkers()",tick);
    }*/

    google.maps.event.addListenerOnce(map, 'idle', addTodo);
}

function addTodo(){
  google.maps.event.clearListeners(map, 'idle');
  addLatas();
  addEstadio();
  addToros();
  timer=setInterval("animateMarkers()",tick);
}

function addToro(location) {
  var image = 'img/redbull/toro_redbull.png';
  marker = new google.maps.Marker({
    position: location,
    map: map,
    icon: image,
    draggable: true,
    animation: google.maps.Animation.DROP
  });
  markersArray.push(marker);
}

function addLata(location) {
  var image = 'img/redbull/LATA.png';
  marker = new google.maps.Marker({
    position: location,
    map: map,
    icon: image,
    draggable: true,
    animation: google.maps.Animation.DROP
  });
  //markersArray.push(marker);
}

function addToros() {

  //google.maps.event.removeListenerOnce(map, 'idle', addToros);
  
  // Add 10 markers to the map at random locations
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
    for (var i = 0; i < 10; i++) {
      var latlo = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(),southWest.lng() + lngSpan * Math.random());
      //setTimeout(function() {
      addToro(latlo);

    
    }

    refreshRutaAToros();

}

function addLatas() {

  //google.maps.event.removeListenerOnce(map, 'idle', addToros);
  
  // Add 10 markers to the map at random locations
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
    for (var i = 0; i < 10; i++) {
      var latlo = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(),southWest.lng() + lngSpan * Math.random());
      //setTimeout(function() {
      addLata(latlo);

    
    }

    
}

function addEstadio() {

  //google.maps.event.removeListenerOnce(map, 'idle', addToros);
  
  // Add 10 markers to the map at random locations
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();
   
    var image = 'img/redbull/estadio.png';
    var latlo = new google.maps.LatLng(southWest.lat() + latSpan * Math.random(),southWest.lng() + lngSpan * Math.random());
  marker = new google.maps.Marker({
    position: latlo,
    map: map,
    icon: image,
    draggable: true,
    animation: google.maps.Animation.DROP
  });
    
}

function refreshRutaAToros(){
  for (i in markersArray) {

     var latLng=markersArray[i].getPosition();
      
      var flightPlanCoordinates = [
            latLng,
            myLatLng
        ];
        
     puntosEntreOrigenDestino_aleatorio[i] = Math.floor(Math.random()*(puntosEntreOrigenDestino_rango_superior-(puntosEntreOrigenDestino_rango_inferior-1))) + puntosEntreOrigenDestino_rango_inferior;
      //puntosEntreOrigenDestino[i]=rango_inferior;
      var points = getPointsAlongLine(flightPlanCoordinates, puntosEntreOrigenDestino_aleatorio[i]);
  
      pointsMarcadores[i]=points;
   
    }
   minimoEntreOrigenDestino = Math.min.apply(null, puntosEntreOrigenDestino_aleatorio);

}

 function getPointsAlongLine(path, num) {
      var dist = google.maps.geometry.spherical.computeLength(path);
      var seg = dist/num;
      var result = [path[0]];
      while (path.length > 1) {
        path = findNextPoint(path, seg);
        result.push(path[0]);
      }
      return result;
}

function findNextPoint(path, seg) {
      if (path.length < 2) {
        return [path[path.length - 1]];
      }
      var leg = google.maps.geometry.spherical.computeLength(path.slice(0, 2));
      if (seg > leg) {
        // point is in the next segment
        return findNextPoint(path.slice(1), seg - leg);
      }
      var target = google.maps.geometry.spherical.interpolate(path[0], path[1], seg/leg);
      path[0] = target;
      return path;
    }

function animateMarkers(){
  
  if(llegadaDelPrimerToro<=minimoEntreOrigenDestino){
  for (i in markersArray) {

      var latLng=markersArray[i].getPosition();
      var points=pointsMarcadores[i];
      markersArray[i].setPosition(points[llegadaDelPrimerToro]);  
      markersArray[i].setAnimation (google.maps.Animation.BOUNCE ); 
  }
  llegadaDelPrimerToro++;
  //timer =setTimeout("animateMarkers()", tick);
  }else{
    llegadaDelPrimerToro=0;
    clearInterval(timer);
    //clearInterval(timerGeoLocation);
    myMarker.setIcon('img/redbull/cutlet.png');
  }
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    myMarker.setIcon('img/redbull/personaje.png');
    markersArray.length = 0;
  }
}